package com.mobile.mo.util;

/**
 * 千锋Java,为你而生！
 *
 * @Author: Feri
 * @Date:2024/11/19 19:35
 * @Modified:
 */
public class CompressUtil {
    /**压缩字符串*/
    public static String compress(String input) {
        if (input == null || input.isEmpty()) {
            return input;
        }

        StringBuilder compressed = new StringBuilder();
        char currentChar = input.charAt(0);
        int count = 1;

        for (int i = 1; i < input.length(); i++) {
            if (input.charAt(i) == currentChar) {
                count++;
            } else {
                compressed.append(currentChar).append(count);
                currentChar = input.charAt(i);
                count = 1;
            }
        }

        // 添加最后一个字符及其计数
        compressed.append(currentChar).append(count);

        // 如果压缩后的字符串比原始字符串长，则返回原始字符串
        return compressed.length() < input.length() ? compressed.toString() : input;
    }
}
